import React, { useRef, useEffect, useState } from 'react';
import { Button, Space, Tooltip } from 'antd';
import {
  ZoomInOutlined,
  ZoomOutOutlined,
  ReloadOutlined,
  ExpandOutlined,
  CompressOutlined,
  TeamOutlined
} from '@ant-design/icons';
import * as d3 from 'd3';

const OrgChartVisualization = ({ 
  nodes = [], 
  edges = [], 
  onNodeClick,
  onEdgeClick,
  editable = false,
  width = '100%',
  height = 500
}) => {
  const svgRef = useRef(null);
  const containerRef = useRef(null);
  const [currentZoom, setCurrentZoom] = useState(1);
  const [expandedNodes, setExpandedNodes] = useState(new Set());

  useEffect(() => {
    if (!nodes.length) return;

    const svg = d3.select(svgRef.current);
    svg.selectAll('*').remove();

    const container = svg.append('g').attr('class', 'orgchart-container');
    
    // 创建缩放行为
    const zoomBehavior = d3.zoom()
      .scaleExtent([0.1, 4])
      .on('zoom', (event) => {
        container.attr('transform', event.transform);
        setCurrentZoom(event.transform.k);
      });

    svg.call(zoomBehavior);

    const containerWidth = containerRef.current?.clientWidth || 800;
    const containerHeight = containerRef.current?.clientHeight || 500;

    // 找到根节点（CEO/总经理）
    const rootNode = nodes.find(node => 
      !edges.some(edge => edge.target === node.id) ||
      node.type === 'ceo' || node.type === 'president'
    ) || nodes[0];

    // 构建组织架构层次结构
    const buildOrgHierarchy = (nodeId, level = 0, visited = new Set()) => {
      if (visited.has(nodeId)) return null;
      visited.add(nodeId);
      
      const node = nodes.find(n => n.id === nodeId);
      if (!node) return null;

      const children = edges
        .filter(edge => edge.source === nodeId)
        .map(edge => buildOrgHierarchy(edge.target, level + 1, visited))
        .filter(child => child !== null);

      return {
        ...node,
        level,
        children,
        expanded: expandedNodes.has(nodeId) || level < 3 // 默认展开前3层
      };
    };

    const hierarchy = buildOrgHierarchy(rootNode.id);
    
    // 组织架构布局算法
    const layoutOrgChart = (node, x, y, width, level = 0) => {
      node.x = x;
      node.y = y;
      
      if (node.children && node.children.length > 0 && node.expanded) {
        const visibleChildren = node.children.filter(child => child.expanded !== false);
        
        if (visibleChildren.length > 0) {
          const childWidth = width / visibleChildren.length;
          const startX = x - width / 2 + childWidth / 2;
          const childY = y + 120; // 固定垂直间距
          
          visibleChildren.forEach((child, index) => {
            const childX = startX + index * childWidth;
            layoutOrgChart(child, childX, childY, childWidth * 0.8, level + 1);
          });
        }
      }
    };

    layoutOrgChart(hierarchy, containerWidth / 2, 80, containerWidth * 0.8);

    // 扁平化节点用于渲染
    const flattenNodes = (node, result = []) => {
      result.push(node);
      if (node.children && node.expanded) {
        node.children.forEach(child => flattenNodes(child, result));
      }
      return result;
    };

    const layoutedNodes = flattenNodes(hierarchy);

    // 创建连接线 - 组织架构特有的直角连接
    const links = container.append('g').attr('class', 'orgchart-links');
    
    const visibleEdges = edges.filter(edge => {
      const source = layoutedNodes.find(n => n.id === edge.source);
      const target = layoutedNodes.find(n => n.id === edge.target);
      return source && target;
    });

    visibleEdges.forEach(edge => {
      const source = layoutedNodes.find(n => n.id === edge.source);
      const target = layoutedNodes.find(n => n.id === edge.target);
      
      if (source && target) {
        const linkGroup = links.append('g');
        
        // 垂直线（从上级向下）
        linkGroup.append('line')
          .attr('x1', source.x)
          .attr('y1', source.y + 30) // 从节点底部开始
          .attr('x2', source.x)
          .attr('y2', target.y - 60) // 到目标节点上方
          .attr('stroke', '#d9d9d9')
          .attr('stroke-width', 2);
        
        // 水平线（连接到下级）
        linkGroup.append('line')
          .attr('x1', source.x)
          .attr('y1', target.y - 60)
          .attr('x2', target.x)
          .attr('y2', target.y - 60)
          .attr('stroke', '#d9d9d9')
          .attr('stroke-width', 2);
        
        // 垂直线（连接到下级节点）
        linkGroup.append('line')
          .attr('x1', target.x)
          .attr('y1', target.y - 60)
          .attr('x2', target.x)
          .attr('y2', target.y - 30)
          .attr('stroke', '#d9d9d9')
          .attr('stroke-width', 2);
      }
    });

    // 创建节点组
    const nodeGroups = container.append('g')
      .attr('class', 'orgchart-nodes')
      .selectAll('g')
      .data(layoutedNodes)
      .enter().append('g')
      .attr('transform', d => `translate(${d.x},${d.y})`)
      .style('cursor', 'pointer')
      .on('click', (event, d) => {
        event.stopPropagation();
        
        // 切换展开/折叠状态
        if (d.children && d.children.length > 0) {
          const newExpandedNodes = new Set(expandedNodes);
          if (expandedNodes.has(d.id)) {
            newExpandedNodes.delete(d.id);
          } else {
            newExpandedNodes.add(d.id);
          }
          setExpandedNodes(newExpandedNodes);
        }
        
        onNodeClick?.(d);
      });

    // 添加阴影滤镜
    const defs = container.append('defs');
    const filter = defs.append('filter')
      .attr('id', 'org-shadow')
      .attr('height', '130%');
    
    filter.append('feDropShadow')
      .attr('dx', 0)
      .attr('dy', 2)
      .attr('stdDeviation', 4)
      .attr('flood-opacity', 0.2);

    // 根据层级和职位绘制不同样式的节点
    nodeGroups.each(function(d) {
      const group = d3.select(this);
      const nodeType = d.type || 'employee';
      const level = d.level || 0;
      
      // 根据职位类型设置颜色和大小
      let nodeColor, nodeWidth, nodeHeight, borderRadius;
      
      switch (nodeType) {
        case 'ceo':
        case 'president':
          nodeColor = '#722ed1';
          nodeWidth = 140;
          nodeHeight = 60;
          borderRadius = 8;
          break;
        case 'vp':
        case 'director':
          nodeColor = '#1677ff';
          nodeWidth = 120;
          nodeHeight = 50;
          borderRadius = 6;
          break;
        case 'manager':
          nodeColor = '#52c41a';
          nodeWidth = 100;
          nodeHeight = 45;
          borderRadius = 6;
          break;
        case 'lead':
          nodeColor = '#fa8c16';
          nodeWidth = 90;
          nodeHeight = 40;
          borderRadius = 4;
          break;
        default:
          nodeColor = '#13c2c2';
          nodeWidth = 80;
          nodeHeight = 35;
          borderRadius = 4;
      }

      // 主节点背景
      group.append('rect')
        .attr('x', -nodeWidth / 2)
        .attr('y', -nodeHeight / 2)
        .attr('width', nodeWidth)
        .attr('height', nodeHeight)
        .attr('rx', borderRadius)
        .attr('fill', nodeColor)
        .attr('stroke', '#fff')
        .attr('stroke-width', 2)
        .attr('filter', 'url(#org-shadow)');

      // 添加头像区域
      if (d.avatar || nodeType !== 'employee') {
        const avatarSize = Math.min(nodeHeight - 8, 32);
        const avatarX = -nodeWidth / 2 + 8;
        const avatarY = -avatarSize / 2;
        
        if (d.avatar) {
          group.append('image')
            .attr('href', d.avatar)
            .attr('x', avatarX)
            .attr('y', avatarY)
            .attr('width', avatarSize)
            .attr('height', avatarSize)
            .attr('clip-path', `circle(${avatarSize/2}px at ${avatarSize/2}px ${avatarSize/2}px)`);
        } else {
          group.append('circle')
            .attr('cx', avatarX + avatarSize / 2)
            .attr('cy', avatarY + avatarSize / 2)
            .attr('r', avatarSize / 2)
            .attr('fill', 'rgba(255,255,255,0.3)')
            .attr('stroke', '#fff')
            .attr('stroke-width', 1);
          
          group.append('text')
            .attr('x', avatarX + avatarSize / 2)
            .attr('y', avatarY + avatarSize / 2)
            .attr('text-anchor', 'middle')
            .attr('dy', '0.35em')
            .attr('font-size', 12)
            .attr('fill', '#fff')
            .text(d.label.charAt(0));
        }
      }

      // 添加姓名
      const textX = d.avatar || nodeType !== 'employee' ? -nodeWidth / 2 + 45 : 0;
      const nameText = group.append('text')
        .attr('x', textX)
        .attr('y', -8)
        .attr('text-anchor', d.avatar || nodeType !== 'employee' ? 'start' : 'middle')
        .attr('fill', '#fff')
        .attr('font-size', 12)
        .attr('font-weight', 'bold')
        .text(d.label);

      // 添加职位
      if (d.position || d.department) {
        group.append('text')
          .attr('x', textX)
          .attr('y', 6)
          .attr('text-anchor', d.avatar || nodeType !== 'employee' ? 'start' : 'middle')
          .attr('fill', 'rgba(255,255,255,0.8)')
          .attr('font-size', 10)
          .text(d.position || d.department);
      }

      // 添加展开/折叠指示器
      if (d.children && d.children.length > 0) {
        const indicator = group.append('g')
          .attr('class', 'expand-indicator')
          .attr('transform', `translate(${nodeWidth / 2 - 12}, ${nodeHeight / 2 - 12})`);
        
        indicator.append('circle')
          .attr('r', 8)
          .attr('fill', '#fff')
          .attr('stroke', nodeColor)
          .attr('stroke-width', 2);
        
        indicator.append('text')
          .attr('text-anchor', 'middle')
          .attr('dy', '0.35em')
          .attr('font-size', 10)
          .attr('fill', nodeColor)
          .attr('font-weight', 'bold')
          .text(d.expanded ? '−' : '+');
        
        // 显示下属数量
        indicator.append('text')
          .attr('x', 0)
          .attr('y', 18)
          .attr('text-anchor', 'middle')
          .attr('font-size', 8)
          .attr('fill', nodeColor)
          .text(d.children.length);
      }

      // 添加部门标签（如果有）
      if (d.department && d.department !== d.position) {
        group.append('rect')
          .attr('x', -nodeWidth / 2)
          .attr('y', nodeHeight / 2 - 15)
          .attr('width', nodeWidth)
          .attr('height', 15)
          .attr('fill', 'rgba(0,0,0,0.1)')
          .attr('rx', `0 0 ${borderRadius} ${borderRadius}`);
        
        group.append('text')
          .attr('x', 0)
          .attr('y', nodeHeight / 2 - 4)
          .attr('text-anchor', 'middle')
          .attr('fill', 'rgba(255,255,255,0.9)')
          .attr('font-size', 8)
          .text(d.department);
      }
    });

    // 添加入场动画
    nodeGroups
      .style('opacity', 0)
      .style('transform', d => `translate(${d.x},${d.y}) scale(0.8)`)
      .transition()
      .duration(600)
      .delay((d, i) => d.level * 200 + i * 50)
      .style('opacity', 1)
      .style('transform', d => `translate(${d.x},${d.y}) scale(1)`);

    links.selectAll('line')
      .style('opacity', 0)
      .transition()
      .duration(400)
      .delay(800)
      .style('opacity', 1);

  }, [nodes, edges, expandedNodes]);

  // 控制函数
  const handleZoomIn = () => {
    const svg = d3.select(svgRef.current);
    svg.transition().call(
      d3.zoom().transform,
      d3.zoomIdentity.scale(currentZoom * 1.2)
    );
  };

  const handleZoomOut = () => {
    const svg = d3.select(svgRef.current);
    svg.transition().call(
      d3.zoom().transform,
      d3.zoomIdentity.scale(currentZoom / 1.2)
    );
  };

  const handleReset = () => {
    const svg = d3.select(svgRef.current);
    svg.transition().call(
      d3.zoom().transform,
      d3.zoomIdentity
    );
    setCurrentZoom(1);
  };

  const handleExpandAll = () => {
    const allNodeIds = new Set(nodes.map(n => n.id));
    setExpandedNodes(allNodeIds);
  };

  const handleCollapseAll = () => {
    setExpandedNodes(new Set());
  };

  return (
    <div style={{ position: 'relative', width, height, border: '1px solid #d9d9d9', borderRadius: '8px', overflow: 'hidden', background: 'linear-gradient(135deg, #fafafa 0%, #f0f2f5 100%)' }}>
      {/* 工具栏 */}
      <div style={{
        position: 'absolute',
        top: '8px',
        right: '8px',
        zIndex: 10,
        background: 'rgba(255, 255, 255, 0.95)',
        borderRadius: '6px',
        padding: '8px',
        boxShadow: '0 2px 8px rgba(0,0,0,0.1)'
      }}>
        <Space size="small">
          <Tooltip title="展开全部">
            <Button size="small" icon={<ExpandOutlined />} onClick={handleExpandAll} />
          </Tooltip>
          <Tooltip title="折叠全部">
            <Button size="small" icon={<CompressOutlined />} onClick={handleCollapseAll} />
          </Tooltip>
          <Tooltip title="放大">
            <Button size="small" icon={<ZoomInOutlined />} onClick={handleZoomIn} />
          </Tooltip>
          <Tooltip title="缩小">
            <Button size="small" icon={<ZoomOutOutlined />} onClick={handleZoomOut} />
          </Tooltip>
          <Tooltip title="重置">
            <Button size="small" icon={<ReloadOutlined />} onClick={handleReset} />
          </Tooltip>
        </Space>
      </div>

      {/* SVG 画布 */}
      <div ref={containerRef} style={{ width: '100%', height: '100%' }}>
        <svg
          ref={svgRef}
          width="100%"
          height="100%"
          style={{ display: 'block' }}
        />
      </div>

      {/* 状态指示器 */}
      <div style={{
        position: 'absolute',
        bottom: '8px',
        left: '8px',
        background: 'rgba(0,0,0,0.7)',
        color: 'white',
        padding: '4px 8px',
        borderRadius: '4px',
        fontSize: '12px'
      }}>
        <Space size="small">
          <TeamOutlined />
          <span>组织架构</span>
          <span>|</span>
          <span>缩放: {Math.round(currentZoom * 100)}%</span>
          <span>|</span>
          <span>人员: {nodes.length}</span>
        </Space>
      </div>
    </div>
  );
};

export default OrgChartVisualization;